from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from .models import Base
from .config import DB_PATH
import os

# Ensure the directory for the DB exists
db_dir = os.path.dirname(DB_PATH)
if not os.path.exists(db_dir):
    os.makedirs(db_dir)

# Use check_same_thread=False for SQLite with Flask/multi-threaded access
engine = create_engine(f'sqlite:///{DB_PATH}', connect_args={"check_same_thread": False}, echo=False)

# Create a globally scoped session factory
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

# Make Base usable within the session context
Base.query = db_session.query_property()

def init_db():
    """Initializes the database and creates tables if they don't exist."""
    # Import all modules here that might define models so they
    # are registered properly on the metadata. Otherwise, you will
    # have dependencies circular import problems.
    # import backend.models # Not strictly needed if Base is imported correctly elsewhere
    try:
        Base.metadata.create_all(bind=engine)
        print("Database initialized successfully.")
    except Exception as e:
        print(f"Error initializing database: {e}")
